<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>课时管理</span>
          <div>
            <el-button
              type="primary"
              icon="Plus"
              class="toolbar-button is-primary"
              @click="handleAdd"
            >新增课时</el-button>
            <el-button
              type="success"
              icon="Sort"
              class="toolbar-button is-success"
              @click="handleSort"
            >排序课时</el-button>
            <el-button
              type="info"
              icon="Back"
              class="toolbar-button is-info"
              @click="goBack"
            >返回上级</el-button>
          </div>
        </div>
      </template>

      <!-- 面包屑导航 -->
      <div class="breadcrumb-nav">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>课程管理</el-breadcrumb-item>
          <el-breadcrumb-item v-if="currentCourse">{{ currentCourse.title }}</el-breadcrumb-item>
          <el-breadcrumb-item v-if="currentChapter">{{ currentChapter.title }}</el-breadcrumb-item>
          <el-breadcrumb-item>课时管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="章节选择" prop="chapterId">
            <el-select v-model="queryParams.chapterId" placeholder="请选择章节" clearable style="width: 200px" @change="handleQuery">
              <el-option
                v-for="chapter in chapterList"
                :key="chapter.id"
                :label="chapter.title"
                :value="chapter.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课时名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入课时名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="课时类型" prop="type">
            <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 120px">
              <el-option label="视频" value="video" />
              <el-option label="文档" value="document" />
              <el-option label="音频" value="audio" />
              <el-option label="直播" value="live" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="草稿" value="0" />
              <el-option label="已发布" value="1" />
              <el-option label="已下架" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="lessonList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
        <el-table-column label="课时信息" align="left" min-width="250">
          <template #default="scope">
            <div class="lesson-info">
              <div class="lesson-title">{{ scope.row.title }}</div>
              <div class="lesson-meta">
                <el-tag :type="getTypeTagType(scope.row.type)" size="small">{{ getTypeText(scope.row.type) }}</el-tag>
                <span class="duration">{{ formatDuration(scope.row.duration) }}</span>
                <span class="text-muted">{{ scope.row.description || '暂无描述' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属章节" align="center" width="180">
          <template #default="scope">
            <span>{{ scope.row.chapterTitle || scope.row.chapterName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学习人数" align="center" width="100">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.studyCount || 0 }}人</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="完成率" align="center" width="100">
          <template #default="scope">
            <div class="progress-info">
              <el-progress
                :percentage="scope.row.completionRate || 0"
                :stroke-width="6"
                :show-text="false"
              />
              <span class="progress-text">{{ scope.row.completionRate || 0 }}%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="info"
                icon="View"
                @click="handleView(scope.row)"
                class="table-operation-button is-info"
                size="small"
              >预览</el-button>
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >编辑</el-button>
              <el-button
                type="success"
                icon="Upload"
                @click="handleUpload(scope.row)"
                class="table-operation-button is-success"
                size="small"
              >上传</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleProgress" icon="DataAnalysis">学习统计</el-dropdown-item>
                    <el-dropdown-item command="handleCopy" icon="DocumentCopy">复制课时</el-dropdown-item>
                    <el-dropdown-item command="handleDelete" icon="Delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改课时对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="lessonFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属章节" prop="chapterId">
              <el-select v-model="form.chapterId" placeholder="请选择章节" style="width: 100%">
                <el-option
                  v-for="chapter in chapterList"
                  :key="chapter.id"
                  :label="chapter.title"
                  :value="chapter.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课时类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="视频课程" value="video" />
                <el-option label="文档资料" value="document" />
                <el-option label="音频课程" value="audio" />
                <el-option label="直播课程" value="live" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="课时名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入课时名称" />
        </el-form-item>
        <el-form-item label="课时描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入课时描述"
            :rows="3"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="时长(分钟)" prop="duration">
              <el-input-number v-model="form.duration" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序号" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" style="width: 100%">
                <el-option label="草稿" :value="0" />
                <el-option label="已发布" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="资源链接" prop="resourceUrl" v-if="form.type !== 'live'">
          <el-input v-model="form.resourceUrl" placeholder="请输入资源链接或上传文件后自动填充" />
        </el-form-item>
        <el-form-item label="直播链接" prop="liveUrl" v-if="form.type === 'live'">
          <el-input v-model="form.liveUrl" placeholder="请输入直播间链接" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文件上传对话框 -->
    <el-dialog title="上传课时资源" v-model="uploadDialogVisible" width="500px" append-to-body>
      <div v-if="currentLesson">
        <div class="upload-info">
          <p><strong>课时名称：</strong>{{ currentLesson.title }}</p>
          <p><strong>课时类型：</strong>{{ getTypeText(currentLesson.type) }}</p>
        </div>
        <el-upload
          ref="uploadRef"
          :action="uploadAction"
          :headers="uploadHeaders"
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :file-list="fileList"
          :limit="1"
          drag
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              <div v-if="currentLesson.type === 'video'">支持 mp4, avi, mov 格式，文件大小不超过 500MB</div>
              <div v-else-if="currentLesson.type === 'audio'">支持 mp3, wav, aac 格式，文件大小不超过 100MB</div>
              <div v-else>支持 pdf, doc, docx, ppt, pptx 格式，文件大小不超过 50MB</div>
            </div>
          </template>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 课时排序对话框 -->
    <el-dialog title="课时排序" v-model="sortDialogVisible" width="500px" append-to-body>
      <div v-if="queryParams.chapterId">
        <p class="sort-tip">拖拽下方课时可调整顺序</p>
        <el-table :data="sortLessonList" row-key="id">
          <el-table-column label="排序" width="80">
            <template #default="scope">
              <el-icon class="drag-handle"><Rank /></el-icon>
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="课时名称" prop="title" />
          <el-table-column label="类型" width="80">
            <template #default="scope">
              <el-tag :type="getTypeTagType(scope.row.type)" size="small">
                {{ getTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="时长" prop="duration" width="80">
            <template #default="scope">
              {{ scope.row.duration }}分钟
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="no-chapter-selected">
        <el-empty description="请先选择章节" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sortDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSort" :disabled="!queryParams.chapterId">保存排序</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Lesson">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Sort, Back, Search, Refresh, View, Edit, Upload, DataAnalysis, DocumentCopy, Delete, Rank, UploadFilled } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getLessonPage,
  getLessonList,
  createLesson,
  updateLesson,
  deleteLesson,
  updateLessonSort,
  uploadLessonVideo,
  getChapterList,
  getCourseList
} from '@/api/classroom'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const open = ref(false)
const uploadDialogVisible = ref(false)
const sortDialogVisible = ref(false)
const title = ref('')
const queryRef = ref()
const lessonFormRef = ref()
const uploadRef = ref()

// 列表数据
const lessonList = ref([])
const chapterList = ref([])
const courseList = ref([])
const sortLessonList = ref([])
const fileList = ref([])
const currentLesson = ref(null)
const currentChapter = ref(null)
const currentCourse = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  chapterId: route.query.chapterId || undefined,
  courseId: route.query.courseId || undefined,
  title: undefined,
  type: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  chapterId: undefined,
  title: undefined,
  description: undefined,
  type: 'video',
  duration: 30,
  sortOrder: 1,
  status: 1,
  resourceUrl: undefined,
  liveUrl: undefined
})

// 表单校验规则
const rules = reactive({
  chapterId: [{ required: true, message: '请选择所属章节', trigger: 'change' }],
  title: [{ required: true, message: '课时名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '请选择课时类型', trigger: 'change' }],
  duration: [{ required: true, message: '课时时长不能为空', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '排序号不能为空', trigger: 'blur' }]
})

// 上传配置
const uploadAction = computed(() => `/api/v1/lessons/${currentLesson.value?.id}/upload`)
const uploadHeaders = computed(() => ({
  'Authorization': 'Bearer ' + localStorage.getItem('token')
}))
const uploadData = computed(() => ({
  lessonId: currentLesson.value?.id
}))

// 获取课时列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getLessonPage(queryParams)
    if (response.code === 200) {
      lessonList.value = response.data.rows || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取课时列表失败')
    }
  } catch (error) {
    console.error('获取课时列表失败:', error)
    ElMessage.error('获取课时列表失败')

    // 模拟数据
    lessonList.value = [
      {
        id: 1,
        chapterId: 'chapter001',
        chapterTitle: '第一章：Java入门',
        title: '1.1 Java简介',
        description: 'Java语言的历史和特点介绍',
        type: 'video',
        duration: 45,
        sortOrder: 1,
        studyCount: 128,
        completionRate: 85,
        status: 1,
        resourceUrl: 'https://example.com/video1.mp4',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        chapterId: 'chapter001',
        chapterTitle: '第一章：Java入门',
        title: '1.2 开发环境搭建',
        description: 'JDK安装和IDE配置',
        type: 'video',
        duration: 60,
        sortOrder: 2,
        studyCount: 95,
        completionRate: 72,
        status: 1,
        resourceUrl: 'https://example.com/video2.mp4',
        createTime: '2024-01-15 11:20:00'
      },
      {
        id: 3,
        chapterId: 'chapter002',
        chapterTitle: '第二章：面向对象编程',
        title: '2.1 类和对象',
        description: '面向对象编程的基本概念',
        type: 'document',
        duration: 30,
        sortOrder: 1,
        studyCount: 76,
        completionRate: 68,
        status: 0,
        resourceUrl: 'https://example.com/doc1.pdf',
        createTime: '2024-01-15 14:15:00'
      }
    ]
    total.value = 3
  } finally {
    loading.value = false
  }
}

// 获取章节列表
const getChapters = async () => {
  try {
    let response
    if (queryParams.courseId) {
      response = await getChapterList(queryParams.courseId)
    } else {
      response = await getChapterList()
    }

    if (response.code === 200) {
      chapterList.value = response.data || []

      // 设置当前章节信息
      if (queryParams.chapterId) {
        currentChapter.value = chapterList.value.find(c => c.id === queryParams.chapterId)
      }
    }
  } catch (error) {
    console.error('获取章节列表失败:', error)
    // 模拟数据
    chapterList.value = [
      { id: 'chapter001', title: '第一章：Java入门', courseId: 'course001' },
      { id: 'chapter002', title: '第二章：面向对象编程', courseId: 'course001' },
      { id: 'chapter003', title: '第三章：异常处理', courseId: 'course001' }
    ]
  }
}

// 获取课程列表
const getCourses = async () => {
  try {
    const response = await getCourseList({ pageNum: 1, pageSize: 100 })
    if (response.code === 200) {
      courseList.value = response.data.rows || []

      // 设置当前课程信息
      if (queryParams.courseId) {
        currentCourse.value = courseList.value.find(c => c.id === queryParams.courseId)
      }
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    // 模拟数据
    courseList.value = [
      { id: 'course001', title: 'Java基础教程' },
      { id: 'course002', title: 'Python数据分析' },
      { id: 'course003', title: 'Vue.js实战' }
    ]
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加课时'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  Object.assign(form, row)
  open.value = true
  title.value = '修改课时'
}

// 查看按钮操作
const handleView = (row) => {
  if (row.resourceUrl) {
    window.open(row.resourceUrl, '_blank')
  } else {
    ElMessage.warning('该课时暂无资源文件')
  }
}

// 上传按钮操作
const handleUpload = (row) => {
  currentLesson.value = row
  fileList.value = []
  uploadDialogVisible.value = true
}

// 返回上级
const goBack = () => {
  if (queryParams.chapterId) {
    router.push({
      path: '/classroom/chapter',
      query: { courseId: queryParams.courseId }
    })
  } else {
    router.push('/classroom/course')
  }
}

// 排序课时
const handleSort = async () => {
  if (!queryParams.chapterId) {
    ElMessage.warning('请先选择章节')
    return
  }

  try {
    const response = await getLessonList(queryParams.chapterId)
    if (response.code === 200) {
      sortLessonList.value = response.data || []
      sortDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取课时列表失败:', error)
    ElMessage.error('获取课时列表失败')
  }
}

// 提交排序
const submitSort = async () => {
  try {
    const lessons = sortLessonList.value.map((item, index) => ({
      id: item.id,
      sortOrder: index + 1
    }))

    const response = await updateLessonSort(queryParams.chapterId, lessons)
    if (response.code === 200) {
      ElMessage.success('排序保存成功')
      sortDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(response.message || '排序保存失败')
    }
  } catch (error) {
    console.error('排序保存失败:', error)
    ElMessage.error('排序保存失败')
  }
}

// 下拉菜单操作
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleProgress':
      handleProgress(row)
      break
    case 'handleCopy':
      handleCopy(row)
      break
    case 'handleDelete':
      handleDelete(row)
      break
  }
}

// 学习统计
const handleProgress = (row) => {
  ElMessage.info('学习统计功能开发中')
}

// 复制课时
const handleCopy = async (row) => {
  try {
    await ElMessageBox.confirm('确定要复制该课时吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const copyData = {
      ...row,
      title: row.title + ' - 副本',
      id: undefined
    }

    const response = await createLesson(copyData)
    if (response.code === 200) {
      ElMessage.success('复制成功')
      getList()
    } else {
      ElMessage.error(response.message || '复制失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('复制失败:', error)
      ElMessage.error('复制失败')
    }
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除课时"' + row.title + '"吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteLesson(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传相关函数
const beforeUpload = (file) => {
  const isValidType = checkFileType(file, currentLesson.value.type)
  const isValidSize = checkFileSize(file, currentLesson.value.type)

  if (!isValidType) {
    ElMessage.error('文件格式不正确')
    return false
  }

  if (!isValidSize) {
    ElMessage.error('文件大小超出限制')
    return false
  }

  return true
}

const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    getList()
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败')
}

// 文件类型检查
const checkFileType = (file, type) => {
  const videoTypes = ['video/mp4', 'video/avi', 'video/mov']
  const audioTypes = ['audio/mp3', 'audio/wav', 'audio/aac']
  const documentTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']

  switch (type) {
    case 'video':
      return videoTypes.includes(file.type)
    case 'audio':
      return audioTypes.includes(file.type)
    case 'document':
      return documentTypes.includes(file.type)
    default:
      return true
  }
}

// 文件大小检查
const checkFileSize = (file, type) => {
  const size = file.size / 1024 / 1024 // MB

  switch (type) {
    case 'video':
      return size <= 500
    case 'audio':
      return size <= 100
    case 'document':
      return size <= 50
    default:
      return size <= 100
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    chapterId: queryParams.chapterId,
    title: undefined,
    description: undefined,
    type: 'video',
    duration: 30,
    sortOrder: 1,
    status: 1,
    resourceUrl: undefined,
    liveUrl: undefined
  })
  lessonFormRef.value?.resetFields()
}

// 提交表单
const submitForm = () => {
  lessonFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          const response = await updateLesson(form.id, form)
          if (response.code === 200) {
            ElMessage.success('修改成功')
          } else {
            ElMessage.error(response.message || '修改失败')
            return
          }
        } else {
          const response = await createLesson(form)
          if (response.code === 200) {
            ElMessage.success('新增成功')
          } else {
            ElMessage.error(response.message || '新增失败')
            return
          }
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 工具函数
const getTypeText = (type) => {
  const typeMap = {
    'video': '视频',
    'document': '文档',
    'audio': '音频',
    'live': '直播'
  }
  return typeMap[type] || '未知'
}

const getTypeTagType = (type) => {
  const typeMap = {
    'video': 'primary',
    'document': 'success',
    'audio': 'warning',
    'live': 'danger'
  }
  return typeMap[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已下架'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDuration = (minutes) => {
  if (!minutes) return '0分钟'
  if (minutes < 60) return `${minutes}分钟`
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  return `${hours}小时${mins}分钟`
}

const parseTime = (time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getCourses()
  getChapters()
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.breadcrumb-nav {
  margin-bottom: 20px;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.lesson-info {
  .lesson-title {
    font-weight: 500;
    color: #303133;
    margin-bottom: 8px;
  }

  .lesson-meta {
    display: flex;
    align-items: center;
    gap: 12px;

    .duration {
      color: #606266;
      font-size: 12px;
      background-color: #f0f2f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;

  .progress-text {
    font-size: 12px;
    color: #606266;
  }
}

.upload-info {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  p {
    margin: 8px 0;
    color: #606266;
  }
}

.sort-tip {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
  text-align: center;
}

.drag-handle {
  cursor: move;
  color: #909399;
  margin-right: 8px;
}

.no-chapter-selected {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  text-align: right;
}

// 分页组件样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: right;
}

// 上传组件样式
:deep(.el-upload-dragger) {
  width: 100%;
}

// 进度条样式
:deep(.el-progress-bar__outer) {
  background-color: #f0f2f5;
}
</style>
